package xmu.crms.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xmu.crms.entity.*;
import xmu.crms.exception.CourseNotFoundException;
import xmu.crms.exception.GroupNotFoundException;
import xmu.crms.exception.UserNotFoundException;
import xmu.crms.service.*;
import xmu.crms.util.JwtUtil;
import xmu.crms.vo.ClassVO;
import xmu.crms.vo.CourseVO;
import xmu.crms.vo.SeminarVO;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zohujain
 * @date 2017/11/28
 */
@RestController
public class CourseController {
    @Autowired
    CourseService courseService;
    @Autowired
    ClassService classService;
    @Autowired
    UserService userService;
    @Autowired
    SeminarService seminarService;
    @Autowired
    SeminarGroupService seminarGroupService;
    @GetMapping("/course")
    public ResponseEntity<List<CourseVO>> getCourseList(@RequestHeader("Authorization") String authString) throws CourseNotFoundException {
        ArrayList<CourseVO> vos = new ArrayList<>();
        BigInteger userId = JwtUtil.getIdFromAuthString(authString);

        List<Course> courses=courseService.listCourseByUserId(userId);
        for(Course each:courses){
            CourseVO courseVO=new CourseVO();
            courseVO.setId(each.getId());
            courseVO.setName(each.getName());
            courseVO.setEndTime(each.getEndDate().toString());
            courseVO.setStartTime(each.getStartDate().toString());
            int number = classService.listClassByCourseId(each.getId()).size();
            courseVO.setNumClass(number);
            vos.add(courseVO);
        }

        return new ResponseEntity<>(vos, HttpStatus.OK);
    }

    @GetMapping("/course/{courseId}")
    public ResponseEntity<CourseVO> getCourseDetail(@PathVariable("courseId") BigInteger courseId)throws CourseNotFoundException ,UserNotFoundException {

        Course course=courseService.getCourseByCourseId(courseId);
        User user=userService.getUserByUserId(course.getTeacher().getId());
        CourseVO vo = new CourseVO();
        vo.setId(course.getId());
        vo.setName(course.getName());
        vo.setDescription(course.getDescription());
        vo.setTeacherEmail(user.getEmail());
        vo.setTeacherName(course.getTeacher().getName());

        return new ResponseEntity<>(vo,HttpStatus.OK);
    }

    @GetMapping("/course/{courseId}/seminar")
    public ResponseEntity<List<SeminarVO>> getSeminar(@PathVariable("courseId") BigInteger courseId,
                                                      @RequestParam(value = "embedGrade", required = false) Boolean embedGrade, @RequestHeader("Authorization") String authString) throws CourseNotFoundException{
        ArrayList<CourseVO> vos = new ArrayList<>();
        BigInteger userId = JwtUtil.getIdFromAuthString(authString);

        List<SeminarVO> list = new ArrayList<>();
        List<Seminar> seminars;

        seminars=seminarService.listSeminarByCourseId(courseId);
        //这里用于日期格式化输出
        SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-M-d");

        for(Seminar each:seminars){
            SeminarVO temp=new SeminarVO();
            temp.setId(each.getId());
            temp.setName(each.getName());
            temp.setDescription(each.getDescription());
            temp.setGroupingMethod(each.getFixed()==true?"fixed":"random");
            temp.setStartTime(bartDateFormat.format(each.getStartTime()));
            temp.setEndTime(bartDateFormat.format(each.getEndTime()));
            if (embedGrade != null && embedGrade) {
                SeminarGroup seminarGroup=new SeminarGroup();
                try {
                    seminarGroup=seminarGroupService.getSeminarGroupById(each.getId(), userId);
                    temp.setGrade(seminarGroup.getFinalGrade());
                }catch(GroupNotFoundException e){
                    //没找到seminarGroup就算了，可能还没组队,找到了就放进去
                    temp.setGrade(0);
                }
            }
            list.add(temp);
        }

        return new ResponseEntity<>(list, HttpStatus.OK);
    }

    @GetMapping("/course/{courseId}/class")
    public ResponseEntity<List<ClassVO>> getCourseClasses(@PathVariable("courseId") BigInteger courseId) throws CourseNotFoundException{

        List<ClassVO> vos = new ArrayList<>();
        List<ClassInfo> classes=classService.listClassByCourseId(courseId);
        for(ClassInfo each:classes){
            ClassVO classVO=new ClassVO();
            classVO.setId(each.getId());
            classVO.setName(each.getName());
            vos.add(classVO);
        }
        return new ResponseEntity<>(vos, HttpStatus.OK);
    }

    /**
     * 这里小程序没有用到，不予处理
     * @param courseId 课程id
     * @return 数据
     */
    @GetMapping("/course/{courseId}/seminar/current")
    public ResponseEntity<SeminarVO> getCurrentSeminar(@PathVariable("courseId") BigInteger courseId) {

        SeminarVO seminar = new SeminarVO();
        seminar.setId(new BigInteger("29"));
        seminar.setName("界面原型设计");
        seminar.setCourseName("OOAD");
        seminar.setGroupingMethod("fixed");
        seminar.setStartTime("2017-09-25");
        seminar.setEndTime("2017-10-09");

        List<ClassVO> classes = new ArrayList<>();
        ClassVO clas = new ClassVO();
        clas.setId(new BigInteger("53"));
        clas.setName("周三12");
        classes.add(clas);

        classes = new ArrayList<>();
        clas = new ClassVO();
        clas.setId(new BigInteger("57"));
        clas.setName("周三34");
        classes.add(clas);

        seminar.setClasses(classes);

        return new ResponseEntity<>(seminar,HttpStatus.OK);
    }
}
